<template>
  <div class="table-sql">
    <je-panel>
      <template #top>
        <div class="sql-title top">{{ $t('TableSqlView.topTitle') }}</div>
        <div class="sql-form">
          <je-form ref="$form" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">
            <je-form-item :label="$t('TableSqlView.queryColumn')" :colon="false" name="column">
              <!--  <je-input
                v-model:value="formState.column"
                :placeholder="$t('TableSqlView.queryPlaceholder')"
              /> -->

              <je-grid-select
                v-model:value="formState.column"
                editable
                name="column"
                :placeholder="$t('TableSqlView.queryPlaceholder')"
                config-info="JE_CORE_TABLECOLUMN,column,TABLECOLUMN_CODE,M"
                :orders="[
                  { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
                  { code: 'SY_ORDERINDEX', type: 'ASC' },
                ]"
                :querys="getJQuery()"
                :select-options="{
                  title: '选择字段',
                  idProperty: 'TABLECOLUMN_CODE',
                  value: formState.column,
                  addQuerys: getJQuery(),
                }"
              />
            </je-form-item>
            <je-form-item :colon="false" name="term">
              <template #label>
                <!-- <je-tooltip v-if="childItem.unitTpl" :title="childItem.unitTpl"> -->
                <i class="conditionicon fas fa-question-circle" @click="clickIcon" />
                {{ $t('TableSqlView.conditionColumn') }}
              </template>
              <je-input
                v-model:value="formState.term"
                :placeholder="`${$t('TableSqlView.conditionPlaceholder')}'{@USER_CODE@}'`"
              />
            </je-form-item>
            <je-row type="flex" justify="space-between">
              <je-col :span="16">
                <je-form-item :label="$t('TableSqlView.orderColumn')" :colon="false">
                  <je-input
                    v-model:value="formState.order"
                    :placeholder="$t('TableSqlView.orderPlaceholder')"
                  />
                </je-form-item>
              </je-col>
              <je-col :span="6">
                <je-form-item
                  :label="$t('TableSqlView.numColumn')"
                  name="num"
                  v-bind="validateInfos.num"
                >
                  <je-select v-model:value="formState.num" editable :filter-option="false">
                    <je-select-option value="10">10</je-select-option>
                    <je-select-option value="20">20</je-select-option>
                    <je-select-option value="30">30</je-select-option>
                    <je-select-option value="40">40</je-select-option>
                    <je-select-option value="50">50</je-select-option>
                    <je-select-option value="60">60</je-select-option>
                    <je-select-option value="70">70</je-select-option>
                    <je-select-option value="80">80</je-select-option>
                    <je-select-option value="90">90</je-select-option>
                    <je-select-option value="100">100</je-select-option>
                  </je-select>
                </je-form-item>
              </je-col>
              <je-col>
                <je-button type="primary" :disabled="queryLoding" @click="clickQuery">
                  <template #icon><i class="fas fa-caret-right"></i></template>
                  {{ $t('TableSqlView.btnText') }}
                </je-button>
              </je-col>
            </je-row>
          </je-form>
        </div>
        <div class="sql-title bottom">
          {{ $t('TableSqlView.bottomTitle') }}
          <span v-if="totalCount > 0" style="color: #d70000; font-size: 14px"
            >（共{{ totalCount }}条数据）</span
          >
          <div class="btn-right">
            <je-dropdown :trigger="['click']">
              <template #overlay>
                <je-menu @click="copySql">
                  <je-menu-item key="selectSql">
                    {{ $t('TableSqlView.btnCopySelectSql') }}
                  </je-menu-item>
                  <je-menu-item key="updateSql">
                    {{ $t('TableSqlView.btnCopyUpdateSql') }}
                  </je-menu-item>
                  <je-menu-item key="deleteSql">
                    {{ $t('TableSqlView.btnCopyDeleteSql') }}
                  </je-menu-item>
                  <je-menu-item key="insterSql">
                    {{ $t('TableSqlView.btnCopyInsterSql') }}
                  </je-menu-item>
                  <je-menu-item key="insterNoSYSql">
                    {{ $t('TableSqlView.btnCopyInsterNoSYSql') }}
                  </je-menu-item>
                </je-menu>
              </template>
              <je-button type="text">
                {{ $t('TableSqlView.btnCopySql') }}
                <i class="fal fa-angle-down"></i>
              </je-button>
            </je-dropdown>
            <je-button type="text" @click="exportSql">
              {{ $t('TableSqlView.btnImportSql') }}
            </je-button>
            <je-button type="text" @click="setColumnWidth">
              {{ $t('TableSqlView.btnTypesetting') }}
            </je-button>
          </div>
        </div>
      </template>
      <template #default>
        <div v-if="columnData.length > 0" class="sql-table">
          <je-table
            ref="xTable"
            :data="tableData1"
            :loading="loading"
            height="100%"
            stripe
            border
            keep-source
            auto-resize
            :row-config="{ isCurrent: true, isHover: true }"
            resizable
            highlight-hover-row
            show-header-overflow
            header-align="center"
            show-overflow="ellipsis"
          >
            <je-column type="seq" width="60" title="NO." align="center"></je-column>
            <je-column
              v-for="data in columnData"
              :key="data.field"
              :width="data.width"
              :field="data.field"
              :title="data.title"
            >
            </je-column>
          </je-table>
        </div>
      </template>
    </je-panel>
  </div>
  <je-modal
    v-model:visible="visibleCondition"
    width="700px"
    title="条件"
    height="auto"
    :resize="false"
    ok-button
    button-align="right"
    :maximizable="false"
  >
    <div>
      条件：是用于查询本资源表数据的过滤条件。输入条件格式与标准的SQL语句一致。<br /><br />
      例：筛选成年用户 （当多个条件时可使用and，or等进行连接查询） user_age > 18 <br />
      例：筛选当前登录人录入的数据（引用系统公有变量） create_usercode = '{@USER_CODE@}'<br /><br />
      说明：系统提供大量的公有变量，当前登录人编码{@USER_CODE@}、当前登录人姓名{@USER_NAME@}等，如果用户信息不能满足,可以通过{@USER.userId@},{@USER.userCode@}这种形式来取当前用户的信息,USER是当前用户对象,具体信息可以查看api;其他的系统变量,用
      {@系统变量名@} 即可获得。
    </div>
  </je-modal>
</template>

<script>
  import { Row, Col } from 'ant-design-vue';
  import { defineComponent, ref, onMounted, reactive, onBeforeMount, nextTick } from 'vue';
  import {
    Input,
    Select,
    Button,
    Grid,
    Modal,
    Panel,
    Form,
    InputSelect,
    Menu,
    Dropdown,
  } from '@jecloud/ui';
  import {
    getColumnData,
    selectByShowSqlView,
    exportByShowSqlView,
    getSqlViewSelect,
  } from '../../api/index';
  import { isNotEmpty, cloneDeep, copy } from '@jecloud/utils';
  import { JE_TABLE_PAGESIZEDATA } from '@/helper/common';
  const useForm = Form.useForm;
  export default defineComponent({
    name: 'TableSql',
    components: {
      JeForm: Form,
      JeInput: Input,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeFormItem: Form.Item,
      JeRow: Row,
      JeCol: Col,
      JeButton: Button,
      JeTable: Grid,
      JeColumn: Grid.Column,
      JePanel: Panel,
      JeModal: Modal,
      JeGridSelect: InputSelect.Grid,
      JeMenu: Menu,
      JeMenuItem: Menu.Item,
      JeDropdown: Dropdown,
    },
    props: {
      tabKey: {
        type: String,
        default: '',
      },
      productData: {
        type: Object,
        required: true,
        default: () => {
          return {};
        },
      },
      tableInfoData: Object,
    },
    setup(props) {
      const xTable = ref(null);
      const pkValue = ref(props.tabKey);
      const loading = ref(true);
      const $form = ref(null);
      const queryLoding = ref(false);
      const formState = reactive({
        column: '',
        term: '',
        order: '',
        num: '30',
      });
      const rulesRef = reactive({
        num: [
          {
            pattern: '^[0-9]*[1-9][0-9]*$',
            message: '请输入大于0的正整数',
          },
        ],
      });

      const { resetFields, validate, validateInfos } = useForm(formState, rulesRef, {
        onValidate: (...args) => {},
      });
      const tableData1 = ref([]);
      const columnData = ref([]);
      const oldColumnData = ref({});
      const oldColumnObj = reactive({});
      const totalCount = ref(0);

      //查询
      const clickQuery = () => {
        columnData.value = [];
        loading.value = true;
        queryLoding.value = true;
        let showColumn = [];
        //做列的显隐
        if (isNotEmpty(formState.column)) {
          formState.column.split(',').forEach((code) => {
            if (oldColumnObj[code]) {
              showColumn.push(oldColumnObj[code]);
            }
          });
        } else {
          showColumn = oldColumnData.value;
        }
        nextTick(() => {
          columnData.value = showColumn;
          validate()
            .then(() => {
              getSqlTableData(true);
            })
            .catch(() => {
              loading.value = false;
              queryLoding.value = false;
            });
        });
      };

      //列数据
      const getColumnDatas = () => {
        const params = {
          tableCode: 'JE_CORE_TABLECOLUMN',
          j_query: JSON.stringify({
            custom: [
              { type: '=', code: 'TABLECOLUMN_RESOURCETABLE_ID', value: pkValue.value },
              { type: '=', code: 'TABLECOLUMN_ISCREATE', value: '1', cn: 'and' },
            ],
            order: [
              { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
              { code: 'SY_ORDERINDEX', type: 'ASC' },
            ],
          }),
          limit: -1,
        };
        getColumnData(params)
          .then((data) => {
            data.rows.forEach((item) => {
              if (item.TABLECOLUMN_NAME && item.TABLECOLUMN_CODE) {
                const columnItem = {
                  field: item.TABLECOLUMN_CODE,
                  title: item.TABLECOLUMN_NAME,
                  type: item.TABLECOLUMN_TYPE,
                  width: 100,
                  show: false,
                };
                columnData.value.push(columnItem);
                oldColumnObj[item.TABLECOLUMN_CODE] = columnItem;
              }
            });
            oldColumnData.value = cloneDeep(columnData.value);
            getSqlTableData();
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };
      //表格数据
      const getSqlTableData = (type) => {
        const params = {
          JE_CORE_RESOURCETABLE_ID: pkValue.value,
          limit: formState.num,
          columns: formState.column || '',
          whereSql: formState.term || '',
          orderSql: formState.order || '',
          SY_PRODUCT_ID: props.productData.productId,
        };
        selectByShowSqlView(params, {
          pd: props.productData.productCode,
        })
          .then((data) => {
            var datas = data.data.rows;
            totalCount.value = data.data.totalCount;
            tableData1.value = datas;
            loading.value = false;
            queryLoding.value = false;
          })
          .catch((e) => {
            loading.value = false;
            queryLoding.value = false;
            tableData1.value = [];
            Modal.alert(e.message, 'error');
          });
      };
      onBeforeMount(() => {
        if (pkValue.value != '' && pkValue.value != undefined) {
          // nextTick(() => {
          getColumnDatas();
          // });
        }
      });
      onMounted(() => {});

      //点击icon
      const visibleCondition = ref(false);
      const clickIcon = () => {
        visibleCondition.value = true;
      };

      //智能排序
      const setColumnWidth = () => {
        const columnArray = [];
        columnData.value.forEach((item) => {
          const field = item.field;
          let num = 0,
            basics = 12,
            width = 0;
          if (item.type == 'ID') {
            basics = 8;
          }
          if (item.type == 'DATETIME') {
            item.width = 160;
          } else if (['SY_CREATETIME', 'SY_MODIFYTIME'].indexOf(field) != -1) {
            item.width = 160;
          } else {
            tableData1.value.forEach((record) => {
              if (num < String(record[field]).length) {
                num = String(record[field]).length;
              }
            });
            width = num * basics;
            if (width > 100) {
              item.width = width;
            }
            if (width > 500) {
              item.width = 500;
            }
            //标题的长度
            const titleWidth = item.title.length * 25;
            if (width < titleWidth && titleWidth > 100) {
              item.width = titleWidth;
            }
          }
          columnArray.push(item);
        });
        columnData.value = columnArray;
        getSqlTableData(true);
      };

      //导出Sql
      const exportSql = () => {
        const params = {
          JE_CORE_RESOURCETABLE_ID: pkValue.value,
          columns: formState.column || '',
          whereSql: formState.term || '',
          orderSql: formState.order || '',
          SY_PRODUCT_ID: props.productData.productId,
        };

        exportByShowSqlView({ params }, { pd: props.productData.productCode })
          .then((data) => {
            if (isNotEmpty(data)) {
              const blob = new Blob([data], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
              });
              const objectUrl = URL.createObjectURL(blob);
              const a = document.createElement('a');
              a.setAttribute('href', objectUrl);
              a.setAttribute('download', props.tableInfoData.RESOURCETABLE_TABLECODE + '.sql');
              a.click();
            } else {
              Modal.alert('没有数据！', 'error');
            }
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      // 复制sql
      const copySql = ({ key }) => {
        const params = {
          RESOURCETABLE_TABLECODE: props.tableInfoData.RESOURCETABLE_TABLECODE,
          columns: formState.column || '',
          whereSql: formState.term || '',
          orderSql: formState.order || '',
          limit: formState.num || '',
          type: key,
        };
        getSqlViewSelect(params)
          .then((data) => {
            copy(data);
            Modal.notice('复制成功！', 'success');
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      //获得列表对象
      const getXTable = () => {
        return xTable.value.$plugin;
      };

      //分装j_query
      const getJQuery = () => {
        const j_query = [
          {
            code: 'TABLECOLUMN_RESOURCETABLE_ID',
            type: '=',
            value: pkValue.value,
            cn: 'and',
          },
          { type: '=', code: 'TABLECOLUMN_ISCREATE', value: '1', cn: 'and' },
        ];
        return j_query;
      };
      return {
        clickQuery,
        labelCol: {
          style: {
            width: '80px',
          },
        },
        wrapperCol: {
          span: 24,
        },
        resetFields,
        formState,
        options: JE_TABLE_PAGESIZEDATA,
        tableData1,
        columnData,
        loading,
        xTable,
        getXTable,
        clickIcon,
        setColumnWidth,
        exportSql,
        totalCount,
        visibleCondition,
        getJQuery,
        $form,
        queryLoding,
        validateInfos,
        copySql,
      };
    },
  });
</script>

<style lang="less" scoped>
  .table-sql {
    height: 100%;
    .sql-title {
      height: 40px;
      background: #f7f9fc;
      line-height: 40px;
      font-size: 14px;
      padding: 0 16px;
      color: #3265f5;
    }
    .sql-title.top {
      border-bottom: 1px solid #e6e6e6;
    }
    .sql-title.bottom {
      position: relative;
      border-top: 1px solid #e6e6e6;
      .btn-right {
        display: inline-block;
        position: absolute;
        right: 0;
      }
    }
    .sql-form {
      padding: 15px 57px 0 32px;
      height: 175px;
      .conditionicon {
        color: #ebebeb;
        cursor: pointer;
        margin-right: 5px;
        &:hover {
          color: #3265f5;
        }
      }
    }
    .sql-table {
      height: 100%;
    }
  }
</style>
<style lang="less">
  .table-sql {
    .sql-table {
      .vxe-table--render-default .vxe-table--border-line {
        border-left: 0 !important;
        border-bottom: 0 !important ;
        border-right: 0 !important ;
      }
    }
  }
</style>
